package org.springblade.flow.repair.parts.listener;

import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.MultiInstanceLoopCharacteristics;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.flow.core.constant.ProcessConstant;
import org.springblade.flow.core.utils.TaskUtil;
import org.springblade.flow.repair.parts.constant.PartsProcessConstant;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 更换配件流程监听器
 * @Author ysq
 * @Date 2022/6/29
 **/
@Slf4j
@Component
public class PartsExecuteListener implements ExecutionListener {

	/**
	 * 角色名称
	 */
	private Expression role;

	/**
	 * 类型：0-申请人所在部门角色人，1-角色所有人
	 */
	private Expression type;

	@Override
	public void notify(DelegateExecution execution) {
		Map<String, VariableInstance> variableInstanceMap = execution.getVariableInstances();
		// 获取流程创建人id
		VariableInstance createUserVariable = variableInstanceMap.get(ProcessConstant.TASK_VARIABLE_CREATE_USER_ID);
		Long createUserId = Long.valueOf(String.valueOf(createUserVariable.getValue()));

		// 维保组长/经理跳过时，设置跳过节点审批人为自己
		if (execution.getCurrentActivityId().equals(PartsProcessConstant.GROUP_TASK)) {
			Object skip=execution.getVariable("skip");
			if (Func.isNotEmpty(skip) && Func.toBoolean(String.valueOf(skip))) {
				execution.setVariable("groupUserList", Arrays.asList(TaskUtil.getTaskUser(String.valueOf(createUserId))));
				return;
			}
		}

		VariableInstance loopCounter = variableInstanceMap.get("loopCounter");
		if (loopCounter == null) {
			FlowElement flowElement = execution.getCurrentFlowElement();
			if (flowElement instanceof UserTask) {
				UserTask userTask = (UserTask) flowElement;
				//判断是不是会签节点
				MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = userTask.getLoopCharacteristics();
				if (multiInstanceLoopCharacteristics != null) {
					log.info(">>>>>>>>>流程监听器,分配任务审批人: {}>>>>>>>>>>>>", execution.getProcessInstanceId());
					IUserService userService = SpringUtil.getBean(IUserService.class);
					String roleName = String.valueOf(role.getValue(execution));
					Integer roleType = Integer.valueOf(String.valueOf(type.getValue(execution)));
					List<Long> userIds;
					if (Func.equalsSafe(0,roleType)) {
						userIds = userService.getUserByOwnDeptParent(createUserId, roleName);
					} else {
						userIds = userService.getUserByRoleName(roleName);
					}

					// 审批人变量名
					String approveUserName = multiInstanceLoopCharacteristics.getInputDataItem();
					// 转换任务用户格式
					List<String> taskUserList = userIds.stream().map(userId -> TaskUtil.getTaskUser(String.valueOf(userId))).collect(Collectors.toList());
					execution.setVariable(approveUserName, taskUserList);
				}
			}
		}
	}
}
